/**
 * 在频繁新建实例并进行日志记录操作的情况下，这个类的时间、空间等性能要略优于LogInfoModel。
 * 
 * Copyright: Copyright (c)2011
 * Company: 易宝支付(YeePay)
 */
package net.loyintean.pearlshell.base.model.impl;

import java.util.Deque;
import java.util.LinkedList;

import net.loyintean.pearlshell.base.model.ILogInfo;

/** 2014-12-21 jun.lin add two methods {@link #start(String)} and {@link #end()}.
 * v2.0.0
 * 
 * @author：jun.lin@yeepay.com
 * @since：2014-12-21
 * @version: 2.0.0 */
class DequeLogInfoModel implements ILogInfo {

	private static final int TAG_SIZE = 2;

	/** 声明为Deque而不是预想的List，是为了使用removeLast方法。 */
	private final Deque<String> logInfo = new LinkedList<String>();

	DequeLogInfoModel(String tagInfo) {
		super();
		logInfo.add(tagInfo);
		logInfo.add(":");
		ensureTagSize();
	}

	@Override
	public String start() {
		ensureTagSize();
		logInfo.add("start!");
		return this.toString();
	}

	@Override
	public String end(String log) {
		ensureTagSize();
		logInfo.add("end! - ");
		logInfo.add(log);

		return this.toString();
	}

	@Override
	public String inner(String log) {
		ensureTagSize();

		logInfo.add("inner! - ");
		logInfo.add(log);
		return this.toString();
	}

	@Override
	public String error(String log) {
		ensureTagSize();

		logInfo.add("error! - ");
		logInfo.add(log);
		return this.toString();
	}

	@Override
	public String error(Throwable e) {
		ensureTagSize();

		logInfo.add("error! - &e=");
		logInfo.add(e.toString());
		return this.toString();
	}

	private void ensureTagSize() {
		if (logInfo.size() > TAG_SIZE) {
			for (int i = logInfo.size(); i > TAG_SIZE; i--) {
				logInfo.removeLast();
			}
		} else if (logInfo.size() < TAG_SIZE) {
			for (int i = logInfo.size(); i < TAG_SIZE; i++) {
				logInfo.add(null);
			}
		}
	}

	@Override
	public String toString() {
		StringBuilder sBuilder = new StringBuilder();
		for (String logItem : logInfo) {
			if (logItem != null) {
				sBuilder.append(logItem);
			}
		}
		return sBuilder.toString();
	}

	/** @see net.loyintean.pearlshell.base.model.ILogInfo#start(java.lang.String) */
	@Override
	public String start(String log) {
		ensureTagSize();
		logInfo.add("start! - ");
		logInfo.add(log);
		return this.toString();
	}

	/** @see net.loyintean.pearlshell.base.model.ILogInfo#end() */
	@Override
	public String end() {
		ensureTagSize();
		logInfo.add("end!");
		return this.toString();
	}

}
